import gdata.youtube
import gdata.youtube.service
import pyblog
from datetime import datetime, timedelta
import time
import sys

def check_or_add_category(blog, categories):
  exists = {}
  live_categories = blog.get_categories()
  for c in live_categories:
    exists[c['categoryName']] = 0
  for c in categories:
    if not exists.has_key(c):
      cat = blog.new_category({'name': c, 'parent_id': 0, 'description': c})

def by_title(v1, v2):
  return cmp(v1['title'], v2['title'])

def by_view_count(v1, v2):
  return cmp(v2['view_count'], v1['view_count'])

def print_videos(videos):
  videos.sort(by_view_count)
  for v in videos:
    print v['title'], v['duration'], v['rating'], v['view_count']

def remove_dupes(videos):
  to_be_removed = []
  videos.sort(by_title)
  m = len(videos)
  for i in range(0,m-1):
    if videos[i]['title'] == videos[i+1]['title']:
      # same title, pick one with more views
      if videos[i]['view_count'] > videos[i+1]['view_count']:
        to_be_removed.append(videos[i+1])
      else:
        to_be_removed.append(videos[i])

  for v in to_be_removed:
    videos.remove(v)
  return videos

def unique_and_order(videos):
  to_be_removed = []
  remove_dupes(videos)
  for v in videos:
    # first, remove anything over 5min (300s)
    if int(v['duration']) > 240:
      to_be_removed.append(v)
    # remove anything that is scored poorly
    if v['rating'] is None or v['rating'] < 4:
      to_be_removed.append(v)

  for v in to_be_removed:
    videos.remove(v)

  videos.sort(by_view_count)
  videos = videos[0:25]

  program_length = 60*20 # 15min long, max
  total_length = 0
  program = []
  for v in videos:
    total_length += v['duration']
    if total_length > program_length: break
    program.append(v)

  videos = program
  return videos


yt_service = gdata.youtube.service.YouTubeService()
yt_service.developer_key = 'your key here'
yt_service.client_id = 'your client id here'
yt_service.email = 'you@gmail.com'
yt_service.password = 'password'
yt_service.source = 'your-app'
yt_service.ProgrammaticLogin()
blog = pyblog.WordPress('http://your-wordpress-blog.com/xmlrpc.php', 'user', 'password')

episode_title = 'Net Nightly News %s' % (datetime.now().strftime("%Y-%m-%d"))

new_public_playlistentry = yt_service.AddPlaylist(episode_title, 'Net Nightly News')

if isinstance(new_public_playlistentry, gdata.youtube.YouTubePlaylistEntry):
  print 'New playlist added'

playlist_id = new_public_playlistentry.id.text.split('/')[-1]

playlist_embed = """
<object width="480" height="385">
  <param name="movie" value="http://www.youtube.com/p/%s"></param>
  <embed src="http://www.youtube.com/p/%s" type="application/x-shockwave-flash" width="480" height="385">
  </embed>
</object>
""" % (playlist_id, playlist_id)

sources = ['AssociatedPress', 'AlJazeeraEnglish', 'CBS']

videos_from_today = []

for s in sources:
  uri = 'http://gdata.youtube.com/feeds/api/videos?author=%s&orderby=published&time=today&racy=include' % s
  feed = yt_service.GetYouTubeVideoFeed(uri)
  for entry in feed.entry:
    video = {}
    dt = datetime(*(time.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.000Z')[0:6]))
    if dt > (datetime.now() - timedelta(hours=12)): 
      continue
    video['id'] = entry.id.text.split('/')[-1]
    video['title'] = entry.media.title.text
    video['description'] = entry.media.description.text
    video['tags'] = [ s.strip() for s in entry.media.keywords.text.split(',') ]
    video['duration'] = int(entry.media.duration.seconds)
    if entry.statistics:
      video['view_count'] = int(entry.statistics.view_count)
    else:
      video['view_count'] = 0

    if entry.rating:
      video['rating'] = float(entry.rating.average)
    else:
      video['rating'] = None

    videos_from_today.append(video)


videos_from_today = unique_and_order(videos_from_today)

#print_videos(videos_from_today)

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/%s' % (playlist_id,)
for video in videos_from_today:
  video_id = video['id']
  playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist(
    playlist_uri, video_id)
  if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
    print 'Video added'

post = blog.new_post({'title': episode_title, 'description': playlist_embed, 'categories': ['World News']})
